package com.mjk.common.util;

import com.google.common.collect.Lists;
import com.google.common.collect.Maps;

import java.util.List;
import java.util.Map;
import java.util.Optional;
import java.util.function.Function;
import java.util.function.Predicate;

/**
 * map - list 
 * list - map
 * @author mjk
 * 转换工具类
 */
public class TransfromUtils {
	
	public static <T> Map<String, T> toMap(List<T> list, final String fileName) {
		return Maps.uniqueIndex(list, (T meetingIssueEntity) ->
				ReflectionUtils.getFieldValue(meetingIssueEntity, fileName).toString());

	}
	
	
	public static <T> List<String> toList(List<T> list, final String fileName){
		return Lists.transform(list,(T t)->{
			if(t instanceof Map){
				return (String)((Map)t).get(fileName);
			}else{
				return ReflectionUtils.getFieldValue(t,fileName).toString();
			}
		});
	}
	/**
	 * 获取数组中某个字段的最小值
	 * @param <T>
	 * @param list
	 * @param fileName
	 * @return
	 */
	public static <T> T minList(List<T> list, final String fileName) {
		Predicate<T> notNullAndNotZero = t -> t != null && !"0".equals(ReflectionUtils.getFieldValue(t, fileName).toString());
		Function<T, Integer> fieldValueToInt = t -> Integer.valueOf(ReflectionUtils.getFieldValue(t, fileName).toString());

		return (T) list.stream()
				.filter(notNullAndNotZero)
				.map(fieldValueToInt)
				.min(Integer::compareTo)
				.map(Optional::of)
				.orElse(Optional.empty());
	}
	
}
